package com.itheima.controller;


import com.aliyuncs.exceptions.ClientException;
import com.itheima.constant.MessageConstant;
import com.itheima.constant.RedisConstant;
import com.itheima.entity.Result;
import com.itheima.utils.SMSUtils;
import com.itheima.utils.ValidateCodeUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;


/**
 * 发送短信验证码的控制层
 */
@RestController
@RequestMapping("/validateCode")
public class ValidateCodeController {

    @Autowired
    private JedisPool jedisPool;

    /**
     * 预约发送验证码
     * @param telephone
     * @return
     */
    @GetMapping("/sendCode")
    public Result sendCode(String telephone){
        try {
            Integer validateCode = ValidateCodeUtils.generateValidateCode(6);
            SMSUtils.sendShortMessage(SMSUtils.VALIDATE_CODE,telephone,validateCode.toString());
            String key=telephone+ RedisConstant.SENDTYPE_ORDER;
            Jedis jedis = jedisPool.getResource();
            jedis.setex(key,600,validateCode.toString());
            jedis.close();
            return Result.success(MessageConstant.SEND_VALIDATECODE_SUCCESS);
        } catch (Exception e) {
            e.printStackTrace();
            return Result.failed(MessageConstant.SEND_VALIDATECODE_FAIL);
        }
    }

    /**
     * 登录验证码发送
     * @param telephone
     * @return
     */
    @PostMapping("/send4Login")
    public Result send4Login(String telephone){
        try {
            Integer code = ValidateCodeUtils.generateValidateCode(6);
            SMSUtils.sendShortMessage(SMSUtils.ORDER_NOTICE,telephone,code.toString());
            Jedis jedis = jedisPool.getResource();
            String key=telephone+RedisConstant.SENDTYPE_LOGIN;
            jedis.setex(key,600,code.toString());
            jedis.close();
            return Result.success(MessageConstant.SEND_VALIDATECODE_SUCCESS);
        } catch (ClientException e) {
            e.printStackTrace();
            return Result.failed(MessageConstant.SEND_VALIDATECODE_FAIL);
        }
    }
}
